package com.tanhua.manager.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Publish;
import com.tanhua.domain.mongo.UserFrozen;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.*;
import com.tanhua.dubbo.api.*;
import lombok.extern.slf4j.Slf4j;

import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserService {

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private PublishApi publishApi;
    @Reference
    private CommentApi commentApi;
    @Reference
    private VideoApi videoApi;
    @Reference
    private UserFrozenApi userFrozenApi;

    /**
     * 用户列表
     */
    public ResponseEntity findUserList(Integer page, Integer pagesize, Long id, String nickname, String city) {
        //获取被封禁的用户的id集合
        List<Long> frozenIds = userFrozenApi.getFrozenIds();
        //更新冻结状态
        userInfoApi.updateUserStatus(frozenIds);
        //1. 查询分页列表
        IPage<UserInfo> iPage = userInfoApi.findUserList(page, pagesize);
        //2. 转换vo
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts((int) iPage.getTotal());
        pageResult.setPages((int) iPage.getPages());
        pageResult.setItems(iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 用户基本资料
     *
     * @param userId 用户详情
     * @return userInfo
     */
    public ResponseEntity findUserById(Long userId) {
        //获取被封禁的用户的id集合
        List<Long> frozenIds = userFrozenApi.getFrozenIds();
        log.info("被冻结的id：{}", frozenIds);
        //更新冻结状态
        userInfoApi.updateUserStatus(frozenIds);
        //1. 查询用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2. 转换vo
        UserInfoVO vo = new UserInfoVO();
        BeanUtils.copyProperties(userInfo, vo);
        vo.setAge(userInfo.getAge().toString());
        vo.setCreated(DateUtil.format(userInfo.getCreated(), "yyyy-MM-dd HH:mm:ss"));
        return ResponseEntity.ok(vo);
    }

    /**
     * 用户动态列表
     *
     * @param userId 用户id
     * @param state  动态审核状态
     *               审核状态，1为待审核，2为自动审核通过，3为待人工审核，4为人工审核拒绝，5为人工审核通过，6为自动审核拒绝
     */
    public ResponseEntity findPublishList(Integer page, Integer pagesize, Long userId, Integer state) {
        //1. 查询动态分页列表
        PageResult pageResult = publishApi.findPublishList(page, pagesize, userId, state);
        List<Publish> items = pageResult.getItems();
        //2. 转换vo
        List<PublishVO> vos = new ArrayList<>();
        for (Publish publish : items) {
            PublishVO vo = new PublishVO();
            UserInfo userInfo = userInfoApi.findById(publish.getUserId());
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());

            BeanUtils.copyProperties(publish, vo);
            vo.setId(publish.getId().toHexString());
            vo.setCreateDate(DateUtil.format(userInfo.getCreated(), "yyyy-MM-dd HH:mm:ss"));
            if (publish.getMedias() != null) {
                vo.setImageContent(publish.getMedias().toArray(new String[]{}));
            }
            vos.add(vo);
        }
        pageResult.setItems(vos);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 动态详情
     *
     * @param publishId 动态id
     */
    public ResponseEntity findPublishById(String publishId) {
        //查询publish
        Publish publish = publishApi.findById(new ObjectId(publishId));
        //转换vo
        PublishVO vo = new PublishVO();
        UserInfo userInfo = userInfoApi.findById(publish.getUserId());
        vo.setUserId(userInfo.getId());
        vo.setAvatar(userInfo.getAvatar());
        vo.setNickname(userInfo.getNickname());

        BeanUtils.copyProperties(publish, vo);
        vo.setCreateDate(DateUtil.format(DateUtil.date(publish.getCreated()), "yyyy-MM-dd HH:mm:ss"));
        if (publish.getMedias() != null) {
            vo.setImageContent(publish.getMedias().toArray(new String[]{}));
        }
        // state 未封装
        return ResponseEntity.ok(vo);
    }

    /**
     * 查询动态或者视频的评论列表
     *
     * @param sortProp  排序字段
     * @param sortOrder 排序规则
     * @param publishId 动态或视频id
     * @return 评论列表
     */
    public ResponseEntity findCommentList(Integer page, Integer pagesize, String sortProp, String sortOrder, String publishId) {
        //1. 查询评论列表
        PageResult pageResult = commentApi.findCommentListByPublishId(page, pagesize, new ObjectId(publishId));
        //2. 转换vo
        List<Comment> items = pageResult.getItems();

        List<CommentVO> vos = new ArrayList<>();
        for (Comment comment : items) {
            CommentVO vo = new CommentVO();
            UserInfo userInfo = userInfoApi.findById(comment.getUserId());
            vo.setNickname(userInfo.getNickname());
            vo.setUserId(userInfo.getId());

            vo.setId(comment.getId().toHexString());
            if (comment.getContent() != null) {
                vo.setContent(comment.getContent());
            }
            vo.setCreateDate(DateUtil.format(DateUtil.date(comment.getCreated()), "yyyy-MM-dd HH:mm:ss"));
            vos.add(vo);
        }
        pageResult.setItems(vos);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 查找用户视频列表
     *
     * @param userId 用户id
     */
    public ResponseEntity findVideoList(Integer page, Integer pagesize, Long userId) {
        PageResult pageResult = videoApi.findVideoList(page, pagesize, userId);
        //转换vo
        List<Video> items = pageResult.getItems();
        List<VideoVO> vos = new ArrayList<>();
        for (Video video : items) {
            VideoVO vo = new VideoVO();
            UserInfo userInfo = userInfoApi.findById(video.getUserId());
            vo.setUserId(userInfo.getId());
            vo.setAvatar(userInfo.getAvatar());
            vo.setNickname(userInfo.getNickname());

            BeanUtils.copyProperties(video, vo);
            vo.setId(video.getId().toHexString());
            vo.setPicUrl(video.getPicUrl());
            vo.setSignature(video.getText());
            vos.add(vo);
        }
        pageResult.setItems(vos);
        return ResponseEntity.ok(pageResult);
    }

    /**
     * 冻结用户操作
     *
     * @return
     */
    public ResponseEntity freezeUser(UserFrozen userFrozen) {
        //修改userinfo表
        userInfoApi.freezeUser(userFrozen.getUserId());
        //存储冻结状态到MongoDB
        userFrozenApi.freezeUser(userFrozen);
        Map<String, String> result = new HashMap<>();
        result.put("message", "操作成功");
        return ResponseEntity.ok(result);
    }

    /**
     * 解封用户
     *
     * @param userId
     * @return
     */
    public ResponseEntity thawUser(Long userId) {
        userFrozenApi.thawUser(userId);
        userInfoApi.unfreezeUser(userId);
        userInfoApi.unfreezeUser(userId);
        userFrozenApi.thawUser(userId);
        Map<String, String> result = new HashMap<>();
        result.put("message", "操作成功");
        return ResponseEntity.ok(result);
    }
    public ResponseEntity dynamicPass(String[] ids) {
        publishApi.dynamicPass(ids);
        Map<String,String> map = new HashMap<>();
        map.put("message","操作成功");
        return ResponseEntity.ok(map);
    }

    public ResponseEntity dynamicRefusal(String[] ids) {
        publishApi.dynamicRefusal(ids);
        Map<String,String> map = new HashMap<>();
        map.put("message","操作成功");
        return ResponseEntity.ok(map);
    }
}
